// Declare the TaskManager Sprints namespace.
TaskManager.Sprints = {}

// Initialize the sprints view.
TaskManager.Sprints.init = function() {
	TaskManager.DataAccess.getSprints(function(sprints) {
		// Initialize the sprints listview.
		$("#sprints-listview").empty().kendoMobileListView({
			dataSource: kendo.data.DataSource.create({
				data: sprints
			}),
			template: kendo.template($("#sprints-listview-template").html())
		});
	});
}



// Declare the TaskManager Sprint namespace.
TaskManager.Sprint = {}

TaskManager.Sprint.show = function(e) {
	TaskManager.Sprint.results(false);
	
	$("#sprint-id").val(e.view.params.id);
	
	TaskManager.DataAccess.getSprintTasks(e.view.params.id, function(tasks) {
		if (tasks.length == 0) {
			$("#sprint-tasks-listview").empty().append($("<li/>").text("There are no tasks defined"));
		} else {
			// Initialize the tasks listview.
			$("#sprint-tasks-listview").empty().kendoMobileListView({
				dataSource: kendo.data.DataSource.create({
					data: tasks
				}),
				template: kendo.template($("#sprint-tasks-listview-template").html())
			});
		}
	});

	var sprint = TaskManager.DataAccess.getSprint(e.view.params.id);

	$("#sprint-start-date").val(Date.fromRaw(sprint.StartDate).toShortDate());
	$("#sprint-end-date").val(Date.fromRaw(sprint.EndDate).toShortDate());
}

TaskManager.Sprint.save = function() {
	try {
		var id = $("#sprint-id").val();
		var sprint = TaskManager.DataAccess.getSprint(id);
		var valid = true;
		
		var start = new Date($("#sprint-start-date").val());
		if ((valid = start != "Invalid Date") == true) {
			sprint.Start = start.toRaw();
			
			var end = new Date($("#sprint-end-date").val());
			if ((valid = end != "Invalid Date") == true) {
				sprint.End = end.toRaw();
			} else {
				TaskManager.Sprint.results(true, "Red", "Invalid End Date");
			}
		} else {
			TaskManager.Sprint.results(true, "Red", "Invalid Start Date");
		}
		
		if (valid) {
			TaskManager.Sprint.results(true, false, "Saving...");
			TaskManager.DataAccess.saveSprint(sprint, function(response) {
				TaskManager.Sprint.results(response.result.length > 0, response.result);
				if (response.result.length == 0) {
					TaskManager.Sprint.results(true, "Green", "Save Complete");

					// After 2 seconds, hide the message.
					setTimeout('$("#sprint-save-results").fadeOut("slow", function() { TaskManager.Sprint.results(false); });', 2000);
				} else {
					TaskManager.Sprint.results(true, "Red", response.result);
				}
			});
		}
	} catch (err) {
		TaskManager.Sprint.results(true, "Red", err);
	}
}

TaskManager.Sprint.results = function(show, color, message) {
	var $results = $("#sprint-save-results");
	
	if (show) {
		$results.css("display", "").css("position", "").css("color", color).text(message);
	} else {
		$results.css("display", "none").css("position", "absolute").text("");
	}
}